<template>
    <div>
      <!-- <div id="video"  class="video_box"></div> -->
      <canvas id="videoCanvas" ref="videoCanvas"></canvas>
      <div class="serve_content">
        <p v-for="(v,i) in serveContent" :key="i">
            {{ v }}
        </p>
      </div>
      <!-- <div class="img"  id="video"> 
        <img :src="imgURL" ref="imgUrl" alt="">
      </div> -->
    </div>
  </template>
   
  <script>
import JMuxer from 'jmuxer'
  export default {
    name: 'VideoStreamDecoder',
    data(){
        return{
            wsUrl:'',
            serveContent:[],
            imgURL:'',
            player:{},
        }
    },
    mounted() {
        this.wsUrl = window.config.wsUrl;
        
        // this.wsUrl = 'ws://127.0.0.1:8080';
        // this.createdCanvas();
        var canvas = document.getElementById('videoCanvas'),
        wfs = new Wfs();
        wfs.attachMedia(canvas,'ch1')
        // this.player= new JSMpeg.Player(this.wsUrl, {canvas: canvas})
    //   this.connectWebSocket();
    },
    methods: {
        init_player(){
            this.player = new JMuxer({
                node: "videoCanvas",
                mode: 'video',
                flushingTime: 1000,
                debug: false,
                onReady: () => {
                return this.get_paused()
                },
            })
        },
        get_paused(){
                this.player.click()
                this.player.play()
        },
        displayFrame(arrayBuffer){
            const blob = new Blob([arrayBuffer]);
        const url = URL.createObjectURL(blob);
        this.$refs.videoCanvas.src = url;
        // YUV到RGB的转换代码（需要根据实际的YUV格式编写）
        // ...
    
        // 使用canvas绘制
        this.ctx.putImageData(uint8Array, 0, 0);
        },
      connectWebSocket() {
        let init = {
            mode: 'toBlob',
            ignoreEditable: true
        };
        // const player = new Broadway.Player(canvas, {
        //     width: 640,
        //     height: 360
        // });
        this.webSocket = new WebSocket(this.wsUrl);
        this.webSocket.binaryType = 'arraybuffer';
        
        this.webSocket.onopen = () => {
          console.log('WebSocket connected');
        //   this.init_player();
        };
   
        this.webSocket.onmessage = (event) => {
            console.log(event)
            this.serveContent.push(event.data);
            // this.displayFrame()
          if (event.data instanceof ArrayBuffer) {
            wfs.attachMedia(this.$refs.videoCanvas,event.data);
            // const videoFrame = new VideoFrame(init, { data: event.data });
            // this.ctx.drawImage(videoFrame, 100, 83);
            // this.renderVideoFrame(event.data);
        //     // 假设你已经有方法将ArrayBuffer转换为ImageData
            // const imageData = this.decodeArrayBufferToImageData(event.data);
            // if (imageData) {
            // this.player.feed({
            // video: new Uint8Array(event.data),
            // })
            // var image = new Image();
            //             image.src = event.data;
            //             image.onload = function() {
            //                 this.ctx.drawImage(imageData, 100, 83);
            //             }
            // }
          }
          else{
            console.log('gettt')
          }
        };
   
        this.webSocket.onerror = (error) => {
          console.error('WebSocket error:', error);
        };
   
        this.webSocket.onclose = () => {
          console.log('WebSocket disconnected');
        };
      },
      createdCanvas(){
        var canvas = document.getElementById('videoCanvas');
        this.ctx = canvas.getContext("2d");
      },
      decodeArrayBufferToImageData(arrayBuffer) {
        let url =  window.btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)))
        return `data:image/png;base64,${url}`
      },
      renderVideoFrame(event) {
        const arrayBuffer = event.data;
        // 假设我们得到的是图片的ArrayBuffer数据
        const blob = new Blob([arrayBuffer]);
        var imageUrl = URL.createObjectURL(blob);

        this.$refs.imgUrl.src = `data:image/png;base64,${imageUrl}`
        }
    },
    beforeDestroy() {
      if (this.webSocket) {
        this.webSocket.close();
      }
    }
  };
  </script>
<style>
#video,#videoCanvas{
    width: 100%;
    height: 300px;
    object-fit: contain;
    background-color: #000;
}
#video img{
    
    position: relative;
}
.serve_content{
    width: 100%;
    height: 200px;
    overflow-y: auto;
}
.serve_content p{
    line-height: 20px;
    font-size: 20px;
}
</style>